package com.gcloud.mesh.alert.dao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.gcloud.framework.db.PageResult;
import com.gcloud.framework.db.dao.impl.JdbcBaseDaoImpl;
import com.gcloud.mesh.alert.entity.HistoryEntity;
import com.gcloud.mesh.header.vo.alert.FlowHistoryVo;
import com.gcloud.mesh.header.vo.dcs.SchedulerJobVo;

@Repository
public class HistoryDao extends JdbcBaseDaoImpl<HistoryEntity, String> {
	public <E> PageResult<E> page(int pageNo, int pageSize, List<String> resourceTypes, Class<E> clazz) {
		StringBuilder sb = new StringBuilder();
		List<Object> values = new ArrayList<>();
		sb.append("SELECT * FROM alert_history");
		if (resourceTypes != null && resourceTypes.size() > 0) {
			sb.append(" WHERE");
			for (String resourceType : resourceTypes) {
				sb.append(" meter like concat('%', ?, '%') OR");
				values.add(resourceType);
			}
			sb = sb.delete(sb.length() - 2, sb.length());
		}
		sb.append(" ORDER BY alert_time DESC ");
		return this.findBySql(sb.toString(), values, pageNo, pageSize, clazz);
	}

	public void clear(Date beforeDate) {
		String sql = "DELETE FROM alert_history WHERE createDate < '" + this.convertDateToString(beforeDate) + "';";
		this.jdbcTemplate.execute(sql);
	}

	private String convertDateToString(Date date) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return dateFormat.format(date);
	}

	public int count(Integer level) {
		StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM alert_history WHERE 1=1");
		if (level != null) {
			sql.append(" AND level=").append(level.toString());
		}
		return this.countBySql(sql.toString(), new ArrayList<Object>());
	}
	
	public PageResult<FlowHistoryVo> flowConut(Integer level, String startTime, String endTime) {
		List<Object> values = new ArrayList<>();
		StringBuilder sql = new StringBuilder("SELECT DATE_FORMAT(alert_time, '%Y-%m-%d') as alert_time, COUNT(*) as sum FROM alert_history WHERE 1=1");
		if (level != null) {
			sql.append(" AND level= ? ");
			values.add(level.toString());
		}
		if (startTime != null && endTime != null) {
			sql.append("AND DATE_FORMAT(alert_time, '%Y-%m-%d') between ? and ? ");
			values.add(startTime);
			values.add(endTime);
		}
		sql.append("GROUP BY DATE_FORMAT(alert_time, '%Y-%m-%d') ORDER BY alert_time desc");
		return this.findBySql(sql.toString(), values, 1, 7, FlowHistoryVo.class);
	}
}
